<template>
  <page-toggle-transition :disabled="animate.disabled" :animate="animate.name" :direction="animate.direction">
    <iframe v-if="!outside" ref="iframe_" :id="id" :src="url" frameborder="0" width="100%" :height="height" scrolling="auto"></iframe>
    <OutsideView v-else />
  </page-toggle-transition>
</template>

<script>
import PageToggleTransition from '../components/transition/PageToggleTransition'
import OutsideView from './OutsideView'
import { mapState } from 'vuex'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from 'store'
export default {
  name: 'IframePageView',
  inject: ['closeCurrent'],
  components: { PageToggleTransition, OutsideView },
  data() {
    return {
      url: '',
      id: '',
      height: '500px',
      outside: false
    }
  },
  computed: {
    ...mapState('setting', ['multiPage', 'animate'])
  },
  updated() {
    !this.outside && this.goUrl()
  },
  watch: {
    $route: {
      handler(to, from) {
        !this.outside && this.goUrl()
      }
    }
  },
  mounted() {
    setTimeout(() => {
      this.setTableHeight()
    }, 100)
  },
  created() {
    this.outside = this.$route.meta?.outside
  },
  methods: {
    goUrl() {
      let url = this.$route.meta.link
      this.id = this.$route.path

      if (url !== null && url !== undefined) {
        /** url支持通过 ${token}方式传递当前登录TOKEN */
        const tokenStr = '${token}'
        if (url.indexOf(tokenStr) !== -1) {
          const token = storage.get(ACCESS_TOKEN)
          url = url.replace(tokenStr, token)
        }
        /** url支持通过 ${token}方式传递当前登录TOKEN */

        /** url拼接路由参数 */
        const query = this.$route.query
        if (Object.keys(query).length) {
          this.setParams(url, query)
        }
        /** url拼接路由参数 */

        this.url = url
      }
    },
    setParams(url, obj) {
      Object.keys(obj).forEach((key, i) => {
        if (url.indexOf('?') === -1) {
          url += `?${key}=${obj[key]}`
        } else {
          url += `&${key}=${obj[key]}`
        }
      })
      return url
    },
    setTableHeight() {
      const clientHeight = document.documentElement.clientHeight
      const tableTop = this.$refs.iframe_.getBoundingClientRect().top
      this.height = clientHeight - tableTop - 40 + 'px'
    }
  }
}
</script>

<style>
</style>
